package com.zds.hj.poseidon.biz.dispatcher.credit;


import com.zds.boot.common.exception.BusinessException;
import com.zds.boot.common.utils.Ids;
import com.zds.boot.common.utils.Strings;
import com.zds.boot.dispatch.annotation.DispatcherHandler;
import com.zds.boot.dispatch.comm.enums.InstructTypeEnum;
import com.zds.boot.dispatch.comm.enums.ModuleNodeTypeEnum;
import com.zds.boot.dispatch.dto.BaseReqModel;
import com.zds.boot.dispatch.dto.BaseResultModel;
import com.zds.boot.dispatch.dto.InstructDto;
import com.zds.boot.dispatch.dto.InstructRegisterModule;
import com.zds.boot.rocketmq.consumer.anotations.RocketListener;
import com.zds.hj.competency.facade.mapping.dto.syxapi.ocr.OcrDistingEnterpriseRespDto;
import com.zds.hj.competency.facade.mapping.dto.syxapi.ocr.OcrDistingReqDto;
import com.zds.hj.crm.facade.dto.customer.req.EnterpriseCustomerReqDto;
import com.zds.hj.crm.facade.dto.customer.resp.EntCustomerCreateQueryRespDto;
import com.zds.hj.crm.facade.dto.customer.resp.EnterpriseCustomerAndExtRespDto;
import com.zds.hj.crm.facade.dto.customer.resp.EnterpriseCustomerRespDto;
import com.zds.hj.icmc.facade.auth.assetcenter.dto.req.EnterpriseRealnameVerifyReqDto;
import com.zds.hj.icmc.facade.auth.assetcenter.dto.resp.AuthRespDto;
import com.zds.hj.icmc.facade.auth.assetcenter.enums.AuditStatusEnum;
import com.zds.hj.icmc.facade.dto.file.FileUploadResultDto;
import com.zds.hj.poseidon.biz.cba.hpp.domain.credit.service.layout.CreditApplyService;
import com.zds.hj.poseidon.biz.common.CompetencyServiceInterface;
import com.zds.hj.poseidon.biz.common.CrmServiceInterface;
import com.zds.hj.poseidon.biz.common.helper.FileUploadTransService;
import com.zds.hj.poseidon.facade.dto.hpp.credit.CreditInfoEntityDto;
import com.zds.hj.product.facade.constant.ApplicationContainerConstant;
import com.zds.zly.common.enums.HjResultCodeEnum;
import com.zds.zly.common.utils.EmptyChecker;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.persistence.Id;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DispatcherHandler(value = "AuthEntInfoEnterHandler", desc = "企业信息录入模块",applicationContainer = ApplicationContainerConstant.FRONT_END, nodeType = ModuleNodeTypeEnum.BUSINESS)
@Slf4j
public class AuthEntInfoEnterHandler extends CreditCheckAbsHandler {

    @Resource
    private CompetencyServiceInterface competencyServiceInterface;

    @Resource
    private CreditApplyService creditApplyService;

    @Resource
    private FileUploadTransService fileUploadTransService;

    @Resource
    private CrmServiceInterface crmServiceInterface;

    private static final String COMPANY_DATA = AuthEntInfoEnterHandler.class.getName() + ".COMPANY_DATA";

    @Override
    public void creditDoExecute(BaseReqModel params, BaseResultModel resultModel, CreditInfoEntityDto reqData, CreditInfoEntityDto dbData) {
        //接受到传入的数据
        log.info("图片识别出来的企业信息-------------------------------"+reqData);
        //进行相关的逻辑判断
        if (Strings.isBlank(reqData.getCompanySocialCredit())){
            throw new BusinessException("统一社会信用代码不能为空", HjResultCodeEnum.PARAMS_VALIDATE_FAIL.getCode());
        }
        if (Strings.isBlank(reqData.getCompanyAddress())){
            throw new BusinessException("公司地址不能为空", HjResultCodeEnum.PARAMS_VALIDATE_FAIL.getCode());
        }
        if (Strings.isBlank(reqData.getEntName())){
            throw new BusinessException("公司名称不能为空", HjResultCodeEnum.PARAMS_VALIDATE_FAIL.getCode());
        }
        if (Strings.isBlank(reqData.getFileId())){
            throw new BusinessException("文件id不能为空", HjResultCodeEnum.PARAMS_VALIDATE_FAIL.getCode());
        }
        //通过产品的id查出applyNo
        CreditInfoEntityDto creditInfoEntityDto = creditApplyService.findCreditOnTransit(params);
        if (EmptyChecker.isEmpty(creditInfoEntityDto)){
            throw new BusinessException("查找授信信息失败",HjResultCodeEnum.NO_DATA_FOUND.getCode());
        }
        //进行企业实名认证
        EnterpriseRealnameVerifyReqDto dto = new EnterpriseRealnameVerifyReqDto();
        //企业名称
        dto.setName(reqData.getEntName());
        //企业证件号
        dto.setCertificateNo(reqData.getCompanySocialCredit());
        //业务流水号
        dto.setThirdSerialNo(creditInfoEntityDto.getApplyNo());
        //渠道编号
        dto.setChannelNo(creditInfoEntityDto.getChannelNo());
        //调用企业认证方法
        AuthRespDto authRespDto = competencyServiceInterface.enterpriseCompanyRealName(dto);
        if (EmptyChecker.isEmpty(authRespDto)){
            throw new BusinessException("未查询到企业相关信息",HjResultCodeEnum.NO_DATA_FOUND.getCode());
        }
        //进行逻辑判断 认证失败抛出异常
        if (authRespDto.getAuditStatusEnum()== AuditStatusEnum.NOT_AUDIT){
            throw new BusinessException("该企业未认证", HjResultCodeEnum.FAIL.getCode());
        }
        if (authRespDto.getAuditStatusEnum()== AuditStatusEnum.AUDITING) {
            throw new BusinessException("该企业在认证中", HjResultCodeEnum.FAIL.getCode());
        }
        if (authRespDto.getAuditStatusEnum()== AuditStatusEnum.APPLY_FAILED) {
            throw new BusinessException("该企业申请失败", HjResultCodeEnum.FAIL.getCode());
        }
        if (authRespDto.getAuditStatusEnum()== AuditStatusEnum.AUDIT_EXPIRE) {
            throw new BusinessException("该企业认证过期", HjResultCodeEnum.FAIL.getCode());
        }
        if (authRespDto.getAuditStatusEnum()== AuditStatusEnum.AUDIT_FAILD) {
            throw new BusinessException("该企业认证失败", HjResultCodeEnum.FAIL.getCode());
        }
        //调用接口用crm保存企业客户信息
        EnterpriseCustomerReqDto enterpriseCustomerReqDto = new EnterpriseCustomerReqDto();
        //企业名称
        enterpriseCustomerReqDto.setEntName(reqData.getEntName());
        //企业证件号
        enterpriseCustomerReqDto.setCreditCode(reqData.getCompanySocialCredit());
        //企业地址
        enterpriseCustomerReqDto.setBusinessAddress(reqData.getCompanyAddress());
        //渠道编号
        enterpriseCustomerReqDto.setChannelNo(params.getChannelNo());
        //强制更新客户名称
        enterpriseCustomerReqDto.setIsForce(true);
        EntCustomerCreateQueryRespDto andQueryServiceDto = crmServiceInterface.createAndQueryService(enterpriseCustomerReqDto);
        //获取到保存的企业客户的id 然后存入数据库中
        Long personId = andQueryServiceDto.getEnterpriseCustomerRespDto().getId();
        //将数据存入数据库中
        dbData.setCompanyAddress(reqData.getCompanyAddress());
        dbData.setEntName(reqData.getEntName());
        dbData.setCompanySocialCredit(reqData.getCompanySocialCredit());
        dbData.setEnterpriseId(personId);
        dbData.setFileId(reqData.getFileId());
    }

    /**
     *分步实现企业信息录入模块
     * @param baseReqModel
     * @return
     */
    @Override
    public BaseResultModel doSection(BaseReqModel baseReqModel) {
        log.info("企业信息录入模块-------------------开始执行");
        //上传文件 返回识别内容fileUploadResultDto
        FileUploadResultDto fileUploadResultDto = fileUploadTransService.fileTransFromObs(baseReqModel.getHttpServletRequest());
        //通过上面的图片识别取出里面的数据存入map里面
        Map<String,Object> map = new HashMap<>();
        map.put("companyName",fileUploadResultDto.getName());
        map.put("companySocialCredit",fileUploadResultDto.getPicNo());
        map.put("companyAddress",fileUploadResultDto.getApplyAddressDetail());
        //上传文件的id
        map.put("fileId",fileUploadResultDto.getFileId());
        BaseResultModel baseResultModel = super.doSection(baseReqModel);
        //将数据放入 baseResultModel 模块里面
        baseResultModel.setResult(map);
        //然后参数摆渡到执行模块
        return baseResultModel;
    }

    /**
     * 将图片识别的信息返给前端
     * @param params
     * @return
     */
    @Override
    public Object echoDetail(BaseReqModel params) {
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,InstructDto> instructMap = params.getDispatchModuleNodes().getInstructSettingMap();
        //是否需要回显
        InstructDto instructDto = instructMap.get(COMPANY_DATA);
        if (instructDto.getValues().equals("是")){
            //查询数据库中的信息
            CreditInfoEntityDto creditInfoEntityDto = creditApplyService.findCreditOnTransit(params);
            if (EmptyChecker.isEmpty(creditInfoEntityDto)){
                throw new BusinessException("查找授信信息失败",HjResultCodeEnum.NO_DATA_FOUND.getCode());
            }
            resultMap.put("companySocialCredit",creditInfoEntityDto.getCompanySocialCredit());
            resultMap.put("companyName",creditInfoEntityDto.getEntName());
            resultMap.put("fileId",creditInfoEntityDto.getFileId());
            return resultMap;
        }
        return null;
    }

    /**
     * 参数摆渡 即模块之间的传参
     * @param o
     * @return
     */
    @Override
    public Object paramsFerry(Object o) {
        CreditInfoEntityDto dbDto =(CreditInfoEntityDto)o;
        CreditInfoEntityDto preData = new CreditInfoEntityDto();
        preData.setEntName(dbDto.getEntName());
        preData.setCompanySocialCredit(dbDto.getCompanySocialCredit());
        preData.setCompanyAddress(dbDto.getCompanyAddress());
        preData.setFileId(dbDto.getFileId());
        return preData;
    }

    /**
     * 回显参数配置
     * @return
     */
    public List<InstructRegisterModule> moduleInstructs() {
        List<InstructRegisterModule> instructRegisterModules = new ArrayList<>();
        InstructRegisterModule registerModule = new InstructRegisterModule();
        registerModule.setInstructCode(COMPANY_DATA);
        registerModule.setInstructName("企业信息录入反显");
        registerModule.setInstructTitle("企业信息录入反显");
        registerModule.setInstructType(InstructTypeEnum.PULL_DOWN_ONE);
        registerModule.setInstructEmphatic("企业信息录入反显");
        registerModule.setValueSource(1);
        registerModule.setInstructValueByCustom("是^否");
        registerModule.setEmptyCheck(true);
        instructRegisterModules.add(registerModule);
        return instructRegisterModules;
    }
}
